package xj.graph2d.app;

import xj.graph2d.CloneManager;
import xj.graph2d.Command;
import xj.graph2d.DrawAttr;
import xj.graph2d.DrawCanvas;
import xj.graph2d.DrawShape;
import xj.graph2d.GraphDocument;
import xj.graph2d.GraphEdgeBase;
import xj.graph2d.SimpleDrawDocument;
import xj.graph2d.SimpleDrawView;
import xj.graph2d.command.RemoveShapeCommand;
import xj.graph2d.tools.PasteTool;

public class EditManager {

  public EditManager(DrawApp app) {
    this.app = app;
    doc = app.getDoc();
    view = app.getView();
    canvas = view.getCanvas();
    pasteTool = new PasteTool();
  }

  public void resetDocView() {
    if (app != null) {
      doc = app.getDoc();
      view = app.getView();
    }
  }

  public void cut() {
    if (debug) {
      System.out.println("EditManager.cut()");
    }

    DrawShape s = doc.getSelectedShape();
    if (s != null) {
      if (debug) {
	System.out.println("EditManager.cut() selected != null");
      }

      shape = s;

      Command cmd;
      cmd = new RemoveShapeCommand(view, doc, shape);
      doc.executeCommand(cmd);
    }
  }

  public void copy() {
    if (debug) {
      System.out.println("EditManager.copy()");
    }

    DrawShape s = doc.getSelectedShape();
    if (s != null) {
      shape = s;
    }
  }

  public void paste() {
    if (debug) {
      System.out.println("EditManager.paste()");
    }

    if (shape != null) {
      DrawShape selected = doc.getSelectedShape();
      doc.setSelectedShape(null);
      canvas.repaintShape(selected);

      GraphDocument graph = null;
      if (doc instanceof GraphDocument) { 
	graph = (GraphDocument) doc; 
      }

      if (graph != null) { 
	CloneManager.startSession();
      }

      try {
	DrawShape newShape = (DrawShape) shape.clone();
	DrawAttr attr = shape.getDrawAttr();
	if (attr != null && 
	    cloneDrawAttr) {
	  attr = (DrawAttr) attr.clone();
	}
	newShape.setDrawAttr(attr);
	
	pasteTool.startPaste(view, newShape);
	
	if (graph != null) { 
	  CloneManager.endSession(graph);
	  if (newShape instanceof GraphEdgeBase) { 
	    GraphEdgeBase edge = (GraphEdgeBase) newShape;
	    if (edge.getSource() != null) { 
	      graph.disconnectSource(edge);
	    }
	    if (edge.getDestination() != null) { 
	      graph.disconnectDestination(edge);
	    }
	  }
	}
      } catch (CloneNotSupportedException e) {
	CloneManager.endSession(graph);
      }

      view.setSpecialTool(pasteTool);
    }
  }

  protected DrawApp app;

  protected SimpleDrawDocument doc;

  protected SimpleDrawView view;

  protected DrawCanvas canvas;

  protected DrawShape shape;

  protected boolean cloneDrawAttr = true;

  protected PasteTool pasteTool;

  protected static final boolean debug = false;

}
